﻿using System;
using System.Linq;
using GC_FFW.BusinessEntities.Abstractions.Interfaces.Forecast;
using GC_FFW.ForecastWriter.Abstractions.Interfaces.Builders;
using GC_FFW.ForecastWriter.Abstractions.Interfaces.Factories;
using GC_FFW.ForecastWriter.Enums;

namespace GC_FFW.ForecastWriter.Builders
{
	public class ForecastBuilder : IForecastBuilder
	{
		#region Variables

		private readonly IProposalAdapterFactory _adapterFactory;

		#endregion

		#region Constructors

		public ForecastBuilder(IProposalAdapterFactory adapterFactory)
		{
			if (adapterFactory == null)
				throw new ArgumentNullException(string.Format("Proposal Adapter Factory"));
			_adapterFactory = adapterFactory;
		}

		#endregion

		#region IForecastBuilder Members

		public string Generate(IForecastData forecastData, IForecastStructure<TeamMatchProposalType> forecastStructure)
		{
			if (forecastData == null || forecastStructure == null || forecastStructure.Paragraphs == null) return string.Empty;

			var forecast = string.Empty;

			forecastStructure.Paragraphs.OrderBy(p => p.Order).ToList().ForEach(p =>
			{
				if (p.Proposals != null && p.Proposals.Any())
				{
					p.Proposals.OrderBy(pr => pr.Order).ToList().ForEach(pr =>
					{
						var adapter = _adapterFactory.Create(pr.Type, forecastData);
						var text = adapter.GetText();
						if (!string.IsNullOrWhiteSpace(text))
							forecast = string.Format("{0}{1} ", forecast, text);
					});

					if (!string.IsNullOrWhiteSpace(forecast))
						forecast = string.Format("{0}\n\n", forecast);
				}
			});

			return forecast;
		}

		#endregion
	}
}
